package com.xuyifeng.callfilter;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/* An adapter to display customized view */
class BlackListCursorAdapter extends CursorAdapter {
	private Context m_context;

	BlackListCursorAdapter(Context context, Cursor c) {
		super(context, c);
		m_context = context;
	}

	BlackListCursorAdapter(Context context, Cursor c, boolean autoRequery) {
		super(context, c, autoRequery);
		m_context = context;
	}

	@Override
	public void bindView (View view, Context context, Cursor cursor) {
		setViewData(view, cursor);
	}

	@Override
	public View	newView(Context context, Cursor cursor, ViewGroup parent)
	{
		RelativeLayout view;

		view = new RelativeLayout(context);
		String inflater = Context.LAYOUT_INFLATER_SERVICE;
		LayoutInflater vi = (LayoutInflater)context.getSystemService(inflater);
		vi.inflate(R.layout.black_list_item, view, true);
		setViewData(view, cursor);

		return view;
	}

	private void setViewData(View view, Cursor cursor) {
		TextView phoneView = (TextView)view.findViewById(R.id.blocked_phone_number);
		TextView nameView = (TextView)view.findViewById(R.id.blocked_display_name);
		TextView memoView = (TextView)view.findViewById(R.id.memo_text);
		String phoneStr = cursor.getString(cursor.getColumnIndexOrThrow(FilterDBAdapter.KEY_ID));
		phoneView.setText(phoneStr);
		nameView.setText(ContactsUtils.getContactNameFromNumber(m_context,phoneStr));
		String memoStr = cursor.getString(cursor.getColumnIndexOrThrow(FilterDBAdapter.KEY_MEMO));
		memoView.setText(memoStr);
	}
}

public class BlackListActivity extends Activity {
	static final private int MENU_REMOVE_ITEM = Menu.FIRST + 1;
	static final private int MENU_EDIT_ITEM = Menu.FIRST + 2;
	static final private int PICK_CONTACT = 1;
	static final private int PICK_CALL_LOG = 2;
	static final private int DIALOG_INPUT_PHONE = 1;
	static final private int DIALOG_EDIT_PHONE = 2;

	FilterDBAdapter m_dbAdapter;
	Cursor m_cursor;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.black_list_view);

		m_dbAdapter = new FilterDBAdapter(this);
		// Open or create the database
		m_dbAdapter.open();

		//m_dbAdapter.enqueueLog("123", "aaa");
		ListView listView = (ListView)findViewById(R.id.blocked_list_view);
		m_cursor = m_dbAdapter.getAllBlackListCursor();
		startManagingCursor(m_cursor);
		BlackListCursorAdapter adapter = new BlackListCursorAdapter(this, m_cursor);
		listView.setAdapter(adapter);
		View view = findViewById(android.R.id.empty);
		listView.setEmptyView(view);
		registerForContextMenu(listView);
	}

	@Override
	protected void onDestroy() {
		m_cursor.close();
		m_dbAdapter.close();
		super.onDestroy();
	}


	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_INPUT_PHONE: {
			final Dialog dialog = new Dialog(this);
			
			dialog.setContentView(R.layout.input_phone);
			dialog.setTitle(R.string.title_input_phone);
			Button btn = (Button) dialog.findViewById(R.id.okBtn);
			btn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					EditText edPhone = (EditText)dialog.findViewById(R.id.ed_phone_number);
					EditText edMemo = (EditText)dialog.findViewById(R.id.ed_memo);
					String strPhone = edPhone.getText().toString().trim();
					String strMemo = edMemo.getText().toString().trim();
					if (strPhone.length() != 0) {
						m_dbAdapter.insertBlackList(strPhone, strMemo);
						m_cursor.requery();
					}
					dialog.dismiss();
				}
			});
			return dialog;
		}
		case DIALOG_EDIT_PHONE: {
			final Dialog dialog = new Dialog(this);
			dialog.setContentView(R.layout.edit_phone);
			dialog.setTitle(R.string.title_edit);
			Button btn = (Button) dialog.findViewById(R.id.okBtn);
			btn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					EditText edPhone = (EditText)dialog.findViewById(R.id.ed_phone_number);
					EditText edMemo = (EditText)dialog.findViewById(R.id.ed_memo);
					String strPhone = edPhone.getText().toString().trim();
					String strMemo = edMemo.getText().toString().trim();
					if (strPhone.length() != 0) {
						m_dbAdapter.updateBlackListMemo(strPhone, strMemo);
						m_cursor.requery();
					}
					dialog.dismiss();
				}
			});
			return dialog;
		}
		default:
			return null;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.blackwhite_list_menu, menu);
		return true;
	}

	@Override
	public void onPrepareDialog(int id, Dialog dialog) {
		switch(id) {
		case (DIALOG_INPUT_PHONE) :
		case (DIALOG_EDIT_PHONE) :
			WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
	    	lp.copyFrom(dialog.getWindow().getAttributes());
	    	lp.width = WindowManager.LayoutParams.FILL_PARENT;
	    	lp.height = WindowManager.LayoutParams.FILL_PARENT;
	    	dialog.getWindow().setAttributes(lp);
	    	EditText edPhone = (EditText)dialog.findViewById(R.id.ed_phone_number);
	    	if (id == DIALOG_INPUT_PHONE)
	    		edPhone.setText("");
	    	else if (id == DIALOG_EDIT_PHONE)
	    	{
				String phone = m_cursor.getString(m_cursor.getColumnIndexOrThrow(FilterDBAdapter.KEY_ID));
	    		edPhone.setText(phone);
	    		String memo = m_cursor.getString(m_cursor.getColumnIndexOrThrow(FilterDBAdapter.KEY_MEMO));
	    		EditText edMemo = (EditText)dialog.findViewById(R.id.ed_memo);
	    		edMemo.setText(memo);
	    	}
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case (R.id.add_from_call_log):
			pickCallLog();
			return true;
		case (R.id.add_from_contacts):
			pickContact();
			return true;
		case R.id.add_phone_number:
			showDialog(DIALOG_INPUT_PHONE);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu,
			View v, ContextMenu.ContextMenuInfo _menuInfo) {
		super.onCreateContextMenu(menu, v, _menuInfo);

		String strPhone = m_cursor.getString(m_cursor.getColumnIndexOrThrow(FilterDBAdapter.KEY_ID));
		menu.setHeaderTitle(strPhone);
		menu.add(0, MENU_REMOVE_ITEM, Menu.NONE, R.string.menu_remove_item);
		menu.add(0, MENU_EDIT_ITEM, Menu.NONE, R.string.menu_edit_item);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		super.onContextItemSelected(item);
		switch (item.getItemId()) {
		case MENU_REMOVE_ITEM: {
			String strPhone = m_cursor.getString(m_cursor.getColumnIndexOrThrow(FilterDBAdapter.KEY_ID));
			m_dbAdapter.removeBlackList(strPhone);
			m_cursor.requery();
			return true;
		}
		case MENU_EDIT_ITEM: 
			showDialog(DIALOG_EDIT_PHONE);
			return true;
		}
		return false;
	}

	private void pickContact() {
		Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
		startActivityForResult(intent, PICK_CONTACT);
	}

	private void pickCallLog() {
		Intent intent = new Intent(this, CallLogPicker.class);
		startActivityForResult(intent, PICK_CALL_LOG);
	}

	@Override
	public void onActivityResult(int reqCode, int resCode, Intent data) {
		super.onActivityResult(reqCode, resCode, data);
		switch(reqCode) {
		case (PICK_CONTACT) : 
			if (resCode == Activity.RESULT_OK) {
				Uri contactDataUri = data.getData();
				ContentResolver resolver = getContentResolver();
				Cursor cursContact = resolver.query(contactDataUri, null, null, null,null);

				if (cursContact.moveToFirst()) {
					String id = cursContact.getString(cursContact.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
					Cursor cursPhone = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
					if (cursPhone.moveToFirst()) {
						do {
							String phoneNum = cursPhone.getString(cursPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
							m_dbAdapter.insertBlackList(phoneNum, "");
						} while(cursPhone.moveToNext());

						m_cursor.requery();
					}
					cursPhone.close();
				}
				cursContact.close();
			}
			break;
		case PICK_CALL_LOG:
			if (resCode == Activity.RESULT_OK) {
				String phoneNum = data.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
				m_dbAdapter.insertBlackList(phoneNum, "");
				m_cursor.requery();
			}
		}
	}
}
